<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div class="searchWrap">
        <div class="searchBox"><span>状态：</span>
          <div @click="selectAll('activeNum')"
               class="searchItem"
               :class="activeNum===null ? 'active':''">全部
          </div>
          <div @click="searchByStatus(item.code,index)" class="searchItem"
               :class="activeNum === index ? 'active':''" v-for="(item,index) in statusList"
               :key="item.code">{{ item.title }}
          </div>
        </div>
      </div>
      <div class="searchWrap">
        <div class="searchBox"><span>项目类型：</span>
          <div @click="selectAll('typeActiveNum')"
               class="searchItem"
               :class="typeActiveNum===null ? 'active':''">全部
          </div>
          <div @click="searchByType(item.code,index)" class="searchItem"
               :class="typeActiveNum === index ? 'active':''" v-for="(item,index) in porTypeList"
               :key="item.code">{{ item.title }}
          </div>
        </div>
      </div>
    </el-card>
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form :model="where" class="ele-form-search" label-width="77px" @keyup.enter.native="reload"
               @submit.native.prevent>

        <el-row >
          <el-col :span="12">
            <el-form-item label="项目名称:">
              <el-input v-model="where.name" clearable placeholder="请输入关键词" style="width: 350px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编号:">
              <el-input v-model="where.project_number" clearable placeholder="请输入项目编号" style="width: 350px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="workplace">
            <el-form-item label="施工地点:">
              <city @areaChange="areaChange" v-model="city" :ids="cityName" ref="city" style="width: 350px"></city>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="workplace">
            <el-form-item label="项目时间:">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                :clearable="false"
                range-separator="至"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="ele-form-actions">
              <el-button v-if="permission.includes('sys:projectList:index')" class="ele-btn-icon" icon="el-icon-search"
                         type="primary" @click="reload">
                查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 数据表格 -->
      <ele-pro-table ref="table" :columns="columns" :datasource="url" :selection.sync="selection" :where="where"
                     height="calc(100vh - 488px)">
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="openEdit(null)"
                     v-if="permission.includes('sys:projectList:add')">新建项目
          </el-button>
        </template>
        <template slot="user_ids" slot-scope="{row}">
          {{
            row.users ? row.users.map(item => {
              return item.user_name
            }).join(' ') : ''
          }}
        </template>
        <!--项目编号-->
        <template slot="project_number" slot-scope="{row}">
          <span style="cursor: pointer;color: var(--color-primary);position: relative"
                @click="$router.push(`/project/projectList/info?id=${row.id}&name=${row.name}&percent_residue=${row.percent_residue}&project_number=${row.project_number}&plan_work_hour=${row.plan_work_hour}&is_charge_person=${row.is_charge_person}`)">
            {{ row.project_number }}
            <el-tag style="position: absolute;right:-38px" v-if="row.postpone" type="danger" size="mini">延期</el-tag>
          </span>
        </template>
        <!--项目名称-->
        <template v-slot:name="{row}">
          {{ row.name }}
        </template>

        <!--计划工期-->
        <template v-slot:plan_day="{row}">
          {{ row.plan_day }} 天
        </template>

        <template v-slot:status="{row}">
          <!--          <span>{{row.status}}</span>-->
          <el-select :value="row.status" placeholder="请选择" @change="(val)=>onChangeStatus(val,row)">
            <el-option
              value="未开始">
            </el-option>
            <el-option
              value="进行中">
            </el-option>
            <el-option
              value="已完成">
            </el-option>
            <el-option
              value="已关闭">
            </el-option>
          </el-select>
        </template>
        >
        <!--创建方式-->
        <template slot="createType">
          <span>客户创建</span>
        </template>
        <!--地址-->
        <template slot="address" slot-scope="{row}">
          <span>{{ row.province_name }} {{ row.city_name }} {{ row.county_name }} {{ row.address }}</span>
        </template>

        <template slot="action" slot-scope="{row}" title="删除" :destroy-on-close="true">
          <div style="display: flex;justify-content: space-between">
            <el-tooltip content="开始项目" :open-delay="750" placement="top">
              <span>
                <i class="el-icon-video-play"
                   :class="row.show_start&&row.is_charge_person?'default':'disabled'"
                   @click="start(row.id)"
                ></i>
              </span>
            </el-tooltip>
            <el-tooltip content="关闭项目" :open-delay="700" placement="top">
              <span>
                <i class="el-icon-switch-button"
                   :class="row.show_close&&row.is_charge_person?'default':'disabled'"

                   @click="close(row)"
                ></i>
              </span>

            </el-tooltip>
            <el-tooltip content="完成项目" :open-delay="700" placement="top">
              <span>
                <i class="el-icon-finished"
                   :class="row.show_complete&&row.is_charge_person?'default':'disabled'"

                   @click="complete(row)"
                ></i>
              </span>

            </el-tooltip>
            <el-tooltip content="编辑项目" :open-delay="700" placement="top">
              <span>
                 <i class="el-icon-edit-outline"
                    :class="row.show_modify?'default':'disabled'"

                    @click="openEdit(row)"
                 ></i>
              </span>

            </el-tooltip>
            <el-tooltip content="删除项目" :open-delay="700" placement="top">
              <span>
                 <el-popconfirm
                   @confirm="confirmDel(row.id)"
                   :class="row.show_delete&&row.is_charge_person?'default':'disabled'"
                   title="确认删除该项目？"
                 >
                <div slot="reference">
                  <i class="el-icon-delete"
                     :class="row.show_delete&&row.is_charge_person?'default':'disabled'"
                  ></i>
                </div>
              </el-popconfirm>
              </span>

            </el-tooltip>
            <el-tooltip content="添加任务" :open-delay="700" placement="top">
              <span>
                <i class="el-icon-circle-plus-outline"
                   :class="row.show_add&&row.is_charge_person?'default':'disabled'"
                   @click="addTask(row)"></i>
              </span>

            </el-tooltip>
            <el-tooltip content="重新开始" :open-delay="700" placement="top">
              <span>
                <el-popconfirm @confirm="confirmRestart(row.id)" title="确认重新开始该项目？"
                               :class="(row.status_text==='已完成'||row.status_text==='已关闭')&&row.is_charge_person?'default':'disabled'">
                <template v-slot:reference>
                  <i class="el-icon-refresh-right"
                     :class="(row.status_text==='已完成'||row.status_text==='已关闭')&&row.is_charge_person?'default':'disabled'"></i>
                </template>
              </el-popconfirm>
              </span>

            </el-tooltip>
            <el-tooltip content="项目归档" :open-delay="700" placement="top">
              <span>
                <el-popconfirm @confirm="confirmArchive(row.id)" title="确认归档该项目？"
                               :class="row.show_filling&&row.is_charge_person?'default':'disabled'">
                <template v-slot:reference>
                  <i class="el-icon-collection"
                     :class="row.show_filling&&row.is_charge_person?'default':'disabled'"></i>
                </template>
              </el-popconfirm>
              </span>

            </el-tooltip>
            <el-tooltip content="甘特图" :open-delay="700" placement="top">
              <span>
                <i class="el-icon-notebook-2"
                   @click="$router.push(`/project/gantt?id=${row.id}`)"
                   :class="row.show_gantt&&row.is_charge_person?'default':'disabled'"
                ></i>
              </span>
            </el-tooltip>
            <el-tooltip content="关联设备" :open-delay="700" placement="top">
              <span>
                <i class="el-icon-link"
                   @click="$refs.associateEquipment.onActivate(row.id)"
                   :class="row.status_text!=='已归档'&&row.status_text!=='已关闭'&&row.status_text!=='已完成'&&row.is_charge_person?'default':'disabled'"
                ></i>
              </span>

            </el-tooltip>
          </div>

        </template>
      </ele-pro-table>
    </el-card>
    <addProject :zones="zones" :statusList="statusList.filter(item=>item.title!=='延期')" ref="projectFormRef" @reload="reload"/>
    <start ref="start" @reload="reload"></start>
    <close ref="close" @reload="reload"></close>
    <addTask :type-list="taskTypeList" ref="addTask" @reload="reload"></addTask>
    <AssociateEquipment ref="associateEquipment" @reload="reload"/>
    <complete ref="complete" @reload="reload"></complete>


  </div>
</template>

<script>
import {mapGetters} from "vuex";
import addProject from './components/addProject.vue'
import Start from "@/views/project/projectList/components/start.vue";
import close from "@/views/project/projectList/components/close.vue";
import addTask from "@/views/project/task/components/addTask.vue";
import AssociateEquipment from "@/views/project/projectList/components/AssociateEquipment.vue";
import city from "@/components/city/index.vue";
import complete from "@/views/project/projectList/components/complete.vue";

export default {
  components: {
    close,
    Start,
    addProject,
    addTask,
    AssociateEquipment,
    city,
    complete
  },
  computed: {
    ...mapGetters(["permission"]),
  },
  watch: {
    dateRange(newQuestion) {
        if (newQuestion == ''||newQuestion == null||newQuestion == []) {
        this.where.date_start = ''
        this.where.date_end = ''
      }
    }
  },
  data() {
    return {
      dateRange: [],
      city: [],
      cityName: '',
      currentId: null,
      // 表格数据接口
      url: '/projects',
      // 表格列配置
      columns: [
        // {
        //   columnKey: 'selection',
        //   type: 'selection',
        //   width: 45,
        //   align: 'center',
        //   fixed: "left"
        // },
        {
          slot: 'project_number',
          label: '项目编号',
          width: 250,
          align: 'center',
          showOverflowTooltip: true,
        },
        {
          slot: 'name',
          label: '项目名称',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center',
        },
        {
          prop: 'customer_name',
          label: '客户',
          showOverflowTooltip: true,
          minWidth: 120,
          align: 'center',
        },
        {
          prop: 'order_number',
          label: '订单号',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center'
        },
        {
          slot: 'user_ids',
          label: '协作人',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center'
        },
        {
          slot: 'address',
          label: '项目地址',
          showOverflowTooltip: true,
          minWidth: 400,
          align: 'center'
        },
        {
          prop: 'zone_name',
          label: '所属区域',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center'
        },
        {
          prop: 'status_text',
          label: '项目状态',
          minWidth: 120,
          align: 'center',
        },
        {
          prop: 'plan_start_at',
          label: '计划开始时间',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center'
        },
        {
          prop: 'plan_complete_at',
          label: '计划结束时间',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center'
        },
        {
          prop: 'entry_at',
          label: '入场时间',
          showOverflowTooltip: true,
          minWidth: 200,
          align: 'center'
        },
        {
          slot: 'plan_day',
          label: '计划工期',
          showOverflowTooltip: true,
          minWidth: 150,
          align: 'center'
        },
        {
          prop: 'schedule_text',
          label: '进度状态',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center'
        },
        {
          prop: 'user_name',
          label: '项目负责人',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          prop: 'task_count',
          label: '任务数量',
          showOverflowTooltip: true,
          minWidth: 120,
          align: 'center'
        },

        {
          prop: 'product_count',
          label: '设备数量',
          showOverflowTooltip: true,
          minWidth: 120,
          align: 'center',
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 260,
          align: 'center',
          resizable: false,
          slot: 'action',
          fixed: "right"
        }
      ],
      loading: false,
      //显示新增联系人
      showCustomerUserEdit: false,
      //显示编辑选项
      isEditType: false,
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      //当前编辑的类型
      type: null,
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      // 二维码是否显示编辑弹窗
      codeEdit: false,
      // 当前编辑数据
      currentCode: null,
      // 是否显示导入弹窗
      showImport: false,
      //客户id
      customer_id: null,
      //客户名字
      customer_name: null,
      //状态搜索激活
      activeNum: null,
      //状态筛选
      statusList: [],
      //类型搜索激活
      statusActiveNum: null,
      btnAfter: false,
      btnBefore: true,
      //对话框
      visible: false,
      taskTypeList: [],
      porTypeList: [
        {title: "我的任务", code: "owner"},
        {title: "我发起的", code: "creator"},
      ],
      typeActiveNum: null,
      zones:[],
    };
  },
  mounted() {
    this.getParams()
    this.queryTaskType()
  },
  methods: {
    /*重新开始项目*/
    async confirmRestart(id) {
      const res = await this.$http.post(`/projects/${id}/re_start`)
      res.data.success ? this.$message.success(res.data.msg) : this.$message.error(res.data.msg);
      this.reload()
    },
    getParams() {
      this.$http.get(`/projects/params`,).then((res) => {
        if (res.data.code === 0) {
          this.statusList = res.data.data.status
          this.zones = res.data.data.zones
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /*省市区*/
    areaChange(val) {
      this.city = val
    },
    /*新建任务/编辑*/
    addTask(row) {
      this.$refs.addTask.showDialog(row);
      this.$forceUpdate()
    },
    /*确认删除项目*/
    async confirmDel(id) {
      const res = await this.$http.delete(`/projects/${id}`)
      res.data.success ? this.$message.success(res.data.msg) : this.$message.error(res.data.msg);
      this.reload()
    },

    async confirmArchive(id) {
      const res = await this.$http.post(`/projects/${id}/filing`)
      res.data.success ? this.$message.success(res.data.msg) : this.$message.error(res.data.msg);
      this.reload()
    },

    async queryTaskType() {
      const res = await this.$http.get(`/tasks/types`)
      res.data.success ? this.taskTypeList = res.data.data.map(item => ({
        value: item,
        label: item
      })) : this.$message.error(res.data.msg)
    },

    /*关闭项目弹窗*/
    close(row) {
      this.$refs.close.active(row)
    },
    complete(row) {
      this.$refs.complete.active(row)
    },
    /*开始项目弹窗*/
    start(id) {
      this.$refs.start.active(id)
    },
    /*显示编辑/新增*/
    openEdit(row) {
      this.$refs.projectFormRef.showDialog(row ? "edit" : "add", row);
      this.$forceUpdate()

    },
    //取消审核
    cancel() {
      this.visible = false
    },
    //完成审核
    done() {
      this.visible = false
      this.reload();
    },
    //上面筛选
    selectAll(key) {
      if (key === "activeNum") {
        this.activeNum = null
        this.where.status = ''
      } else {
        this.typeActiveNum = null
        this.where.type = ''
      }

      this.reload()
    },
    //根据项目状态搜索
    searchByStatus(item, index) {
      this.activeNum = index
      this.handelStatusSearch(item)
    },
    searchByType(item, index) {
      this.typeActiveNum = index
      this.handelTypeSearch(item)
    },
    //项目状态搜索
    handelStatusSearch(item) {
      this.where.status = item
      this.reload()
    },
    //项目类型搜索
    handelTypeSearch(item) {
      this.where.type = item
      this.reload()
    },
    //数据处理
    formProducts(row) {
      return (row.products.map(item => {
        return item?.product?.name
      })).join(' ')
    },
    formMaster(row) {
      if (row.users.filter((item) => {
        return item.is_master === 1
      })) {
        if (((row.users.filter((item) => {
          return item.is_master === 1
        }))[0])) {
          return (((row.users.filter((item) => {
            return item.is_master === 1
          }))[0]).user).realname
        }
      }
    },
    formSynergistic_people(row) {
      return ((row.users.filter((item) => {
        return item.is_master === 0
      })).map(item => {
        return item.user.realname
      })).join(' ')
    },
    /* 刷新表格 */
    reload() {
      if (this.dateRange.length) {
        this.where.date_start = this.dateRange[0]
        this.where.date_end = this.dateRange[1]
      }
      if (this.city.length) {
        this.where.province_id = this.city[0]
        this.where.city_id = this.city[1]
        this.where.county_id = this.city[2]
      }
      this.$refs.table.reload({where: this.where});
    },
    /* 重置搜索 */
    reset() {
      this.dateRange = []
      this.$refs.city.addressIds = ''
      this.btnAfter = false
      this.btnBefore = true
      this.activeNum = null
      this.typeActiveNum = null
      this.statusActiveNum = null
      this.type = ''
      this.isEditType = false;
      this.where = {};
      this.city = ''
      this.url = '/projects'
      this.reload();
    },

    onChangeStatus(val, row) {
      console.log(val, row)
    },

  }
}
</script>

<style scoped lang="scss">
.searchWrap {

}

.active {
  background: var(--color-primary-1);;
  border-color: #d0f3f4;
  color: var(--color-primary);;
  padding: 4px 8px;
}

.searchBox {
  display: flex;

  span {
    color: #a7b5b5;
    display: block;
    width: 110px;
    height: 36px;
    font-size: 16px;
  }

  .searchItem {
    border: 1px solid transparent;
    border-radius: 4px;
    font-size: 13px;
    margin: 0 12px 8px 0;
    max-width: 160px;
    overflow: hidden;
    padding: 4px 8px;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
    font-size: 14px;
  }
}


//查看审核样式
.audit-info {
  margin: 50px 0 0 5px;

  .audit-content {
    padding: 20px;
    padding-left: 50px;
    height: 160px !important;
  }
}

.divider-wrap {
  padding: 10px;
  width: 100%;

  .el-divider ::v-deep span {
    color: #ccc;
  }

}

.btnWrap {
  display: flex;

  .el-button {
    margin-right: 20px;
  }
}

.workplace .el-cascader--medium {
  width: 100%;
}

.disabled {
  color: #90939973;
  pointer-events: none;
  cursor: not-allowed;
  font-size: 22px;
}

.default {
  color: var(--color-primary);
  cursor: pointer;
  font-size: 22px;
}
</style>
